package com.lian.aieduc.utils;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import java.util.Random;

@Component
@RequiredArgsConstructor
public class MailSenderUtil {

    private final JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private final String fromEmail = "2088486180@qq.com";

    /**
     * 发送邮箱验证码
     *
     * @param toEmail 目标邮箱
     */
    public Integer sendEmailCode(String toEmail) throws MessagingException {
        System.out.println("FromEmail:" + fromEmail);
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        // 生成随机验证码
        Random random = new Random();
        Integer code = random.nextInt(900000) + 100000;
        helper.setSubject("您的验证码为：" + String.valueOf(code));
        // 设置从哪发送
        helper.setFrom(fromEmail);
        // 发送给谁
        helper.setTo(toEmail);
        helper.setText("有效时间为5分钟！请尽快使用！");
        helper.setText("您好！，您正在注册智慧教育平台账号。" + "您的验证码为：" + "<h2>" + code + "</h2>", true);
        // 发送邮件
        javaMailSender.send(mimeMessage);
        System.out.println("发送成功");
        return code;
    }

}
